package com.rlz.base.util

import android.text.TextUtils
import com.google.gson.*
import com.google.gson.reflect.TypeToken
import java.util.*

/**
 * Created by RLZ
 * on 2021/3/11
 *
 */
object GSONUtil {

    /**
     * Json 解析器
     */
    private val PARSER = JsonParser()

    private var gson: Gson? = null

    /**
     *
     * 设置一个通用的Gson
     */
    fun setGson(gs: Gson?) {
        gson = gs
    }

    fun getGson(): Gson? {
        if (gson == null) {
            val builder = GsonBuilder()
            builder.serializeNulls()
            builder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
            gson = builder.create()
        }
        return gson
    }

    /**
     * 获取Json对象里面的键, 并将其值以String返回.<br></br>
     * 当值为json对象或者json数组时,返回其json格式的字符串
     *
     */
    fun getString(json: String?, key: String?): String? {
        val element = PARSER.parse(json)
        if (element.isJsonObject) {
            val obj = element.asJsonObject
            val value = obj[key]
            if (value != null) {
                return if (value is JsonPrimitive) {
                    value.getAsString()
                } else if (value is JsonNull) {
                    null
                } else {
                    value.toString()
                }
            }
        }
        return null
    }

    fun getInt(json: String?, key: String?): Int {
        val element = PARSER.parse(json)
        if (element.isJsonObject) {
            val obj = element.asJsonObject
            val value = obj[key]
            if (value != null) {
                return (value as? JsonPrimitive)?.toString()?.toInt()
                    ?: if (value is JsonNull) {
                        0
                    } else {
                        value.toString().toInt()
                    }
            }
        }
        return 0
    }

    /**
     * 将json解析为一个JsonObject
     *
     */
    fun toJsonObject(json: String?): JsonObject? {
        val element = PARSER.parse(json)
        return element.asJsonObject
    }

    /**
     * 将json解析为一个JsonArray
     *
     */
    fun toJsonArray(json: String?): JsonArray? {
        val element = PARSER.parse(json)
        return element.asJsonArray
    }

    /**
     * 将json对象序列化为一个对象实例
     *
     */
    fun <T> toObject(json: String?, clss: Class<T>?): T {
        val gson = getGson()
        return gson!!.fromJson(json, clss)
    }

    /**
     * 将json数组序列化为一个对象的List实例
     *
     */
    fun <T> toJsonFromList(json: String?, clss: Class<T>?): List<T>? {
        val element = PARSER.parse(json)
        if (element.isJsonArray) {
            val gson = getGson()
            val array = element.asJsonArray
            val size = array.size()
            val result = ArrayList<T>(size)
            for (i in 0 until size) {
                val item = array[i]
                val t = gson!!.fromJson(item, clss)
                result.add(t)
            }
            return result
        }
        return null
    }

    /***
     * 将对象转换成相对应的字符串
     *
     */
    fun toJsonFromBean(obj: Any?): String? {
        try {
            val gson = getGson()
            return gson!!.toJson(obj)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }


    /**
     * 将map集合转换成相对应的字符串
     *
     */
    fun <T> toJsonFromMap(map: Map<String?, T>?): String? {
        try {
            val gson = getGson()
            val type: TypeToken<Map<String?, T>?> = object : TypeToken<Map<String?, T>?>() {}
            val json = gson!!.toJson(map, type.type)
            //  LogUtil.d(json.replace("\\", ""));
            return json.replace("\\", "")
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    /**
     * 将list<map></map><>>集合转换成相对应的字符串
     *
     */
    fun <T> toJsonFromListMap(listMaps: List<Map<String?, T>?>?): String? {
        try {
            val gson = getGson()
            val type: TypeToken<List<Map<String?, T>?>?> =
                object : TypeToken<List<Map<String?, T>?>?>() {}
            return gson!!.toJson(listMaps, type.type)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    /**
     * 将json转换成对象
     *
     */
    fun <T> fromJsontoBean(result: String?, clz: Class<T>?): T? {
        return if (TextUtils.isEmpty(result)) {
            null
        } else {
            try {
                val gson = getGson()
                return gson!!.fromJson(result, clz) as T
            } catch (e: JsonSyntaxException) {
                e.printStackTrace()
            }
            null
        }
    }

    /**
     * 将json转换成list
     *
     */
    fun <T> fromJsonToList(result: String?): List<T>? {
        try {
            val gson = getGson()
            val type: TypeToken<List<T>?> = object : TypeToken<List<T>?>() {}
            return gson!!.fromJson(result, type.type)
        } catch (e: JsonSyntaxException) {
            e.printStackTrace()
        }
        return null
    }

    /***
     * 将json转换成map
     *
     */
    fun <T> fromJsonToMap(result: String?): Map<String?, T>? {
        try {
            val gson = getGson()
            val type: TypeToken<Map<String?, T>?> = object : TypeToken<Map<String?, T>?>() {}
            return gson!!.fromJson(result, type.type)
        } catch (e: JsonSyntaxException) {
            e.printStackTrace()
        }
        return null
    }

    /**
     * 将json转换成list<map></map><>>
     *
     */
    fun <T> fromJsonToListMap(result: String?): List<Map<String?, T>?>? {
        try {
            val gson = getGson()
            val type: TypeToken<List<Map<String?, T>?>?> =
                object : TypeToken<List<Map<String?, T>?>?>() {}
            return gson!!.fromJson(result, type.type)
        } catch (e: JsonSyntaxException) {
            e.printStackTrace()
        }
        return null
    }

}